package UILayer;

import java.awt.BorderLayout;

import CtrLayer.OrderCtr;
import ModelLayer.CurrentAccount;
import ModelLayer.CustomerCollection;
import ModelLayer.Stock;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;





import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.UIManager;

public class SaleAdder extends JInternalFrame
{
	/*private JTextField note_tf;
	private JTextField terms_tf;
	private JTextField add_inf_tf;*/
	private JTextField spec_disc_tf;
	private JPanel panel;
	private ArrayList<Object[]> selected;
	private OrderCtr order_ctr;
	//private StockCtr stock_ctr;
	private String customer_id;
	private JCheckBox delivery_checkbox;
	private JCheckBox paid_checkbox;
	private JLabel lblYouMustInsert;
	private boolean is_employee;
	private JTextArea add_inf_ta;
	private JTextArea note_ta;
	private JTextArea terms_ta;
	private JScrollPane scrollPane_1;
	private JScrollPane scrollPane_2;
	private double estimated_cost;

	public SaleAdder(ArrayList<Object[]> i_selected, String i_customer_id, double i_estimated_cost)
	{
		super("Add sale", true, true, true, true);
		selected = i_selected;
		customer_id = i_customer_id;
		estimated_cost = i_estimated_cost;
		is_employee = CurrentAccount.give_rank().equals("employee");
		setBounds(100, 100, 627, 423);
		getContentPane().setLayout(null);
		order_ctr = new OrderCtr();
		panel = new JPanel();
		panel.setBounds(0, 260, 434, 10);
		getContentPane().setLayout(new BorderLayout(0, 0));
		getContentPane().add(panel, BorderLayout.CENTER);
		panel.setLayout(null);

		make_tfs();
		make_lbls();
		make_checkboxes();
		make_btns();

	}

	private void make_checkboxes()
	{
		delivery_checkbox = new JCheckBox("Delivery");
		delivery_checkbox.setBounds(10, 174, 97, 23);
		delivery_checkbox.addItemListener(new ItemListener()
		{
			@Override
			public void itemStateChanged(ItemEvent e)
			{
				if (e.getStateChange() == ItemEvent.SELECTED)
				{
					note_ta.setEnabled(true);
					terms_ta.setEnabled(true);
				}
				else
				{
					note_ta.setText("");
					terms_ta.setText("");
					note_ta.setEnabled(false);
					terms_ta.setEnabled(false);
					
				}
			}
		});
		panel.add(delivery_checkbox);

		paid_checkbox = new JCheckBox("Paid");
		paid_checkbox.setBounds(10, 43, 97, 23);
		panel.add(paid_checkbox);
		
		JLabel lblEstimatedTotalPrice = new JLabel("Estimated total price:");
		lblEstimatedTotalPrice.setBounds(368, 35, 117, 14);
		panel.add(lblEstimatedTotalPrice);
		
		JLabel lblNewLabel = new JLabel("");
		lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 17));
		lblNewLabel.setText(String.valueOf(estimated_cost) + " DKK");
		lblNewLabel.setBounds(477, 32, 112, 14);
		panel.add(lblNewLabel);
		
		

	}

	private void make_btns()
	{
		JPanel panel_2 = new JPanel();
		getContentPane().add(panel_2, BorderLayout.SOUTH);
		panel_2.setLayout(new BorderLayout(0, 0));

		JButton confirm_btn = new JButton("Confirm");
		confirm_btn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				save();
			}
		});
		panel_2.add(confirm_btn, BorderLayout.WEST);

		JButton back_btn = new JButton("Back");
		back_btn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				back();
			}
		});
		panel_2.add(back_btn, BorderLayout.EAST);
	}

	private void make_lbls()
	{
		JLabel lblEnterDetailsOf = new JLabel("Enter details of the sale.");
		lblEnterDetailsOf.setFont(new Font("Times New Roman", Font.BOLD, 14));
		lblEnterDetailsOf.setBounds(10, 11, 160, 14);
		panel.add(lblEnterDetailsOf);

		JLabel note_lbl = new JLabel("Delivery note");
		note_lbl.setBounds(10, 280, 70, 14);
		panel.add(note_lbl);

		JLabel terms_lbl = new JLabel("Delivery terms");
		terms_lbl.setBounds(10, 211, 70, 14);
		panel.add(terms_lbl);

		JLabel add_inf_lbl = new JLabel("Additional information");
		add_inf_lbl.setBounds(10, 116, 112, 14);
		panel.add(add_inf_lbl);
		
		JLabel spec_dis_lbl = new JLabel("Special discount");
		spec_dis_lbl.setBounds(10, 73, 93, 14);
		panel.add(spec_dis_lbl);

		JLabel percent_lbl = new JLabel("%");
		percent_lbl.setBounds(221, 73, 46, 14);
		panel.add(percent_lbl);

		lblYouMustInsert = new JLabel(
				"<html><p>You must insert a correct number or leave this field blank<p><html>");
		lblYouMustInsert.setForeground(Color.RED);
		lblYouMustInsert.setVisible(false);
		lblYouMustInsert.setBounds(248, 70, 184, 33);
		panel.add(lblYouMustInsert);
		
		if(is_employee)
		{
			spec_disc_tf.setEnabled(false);
		}
	}

	private void make_tfs()
	{


		spec_disc_tf = new JTextField();
		spec_disc_tf.setBounds(125, 70, 86, 20);
		panel.add(spec_disc_tf);
		spec_disc_tf.setColumns(10);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(125, 116, 184, 61);
		panel.add(scrollPane);
		
		add_inf_ta = new JTextArea();
		add_inf_ta.setLineWrap(true);
		scrollPane.setViewportView(add_inf_ta);
		
		scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(125, 208, 184, 61);
		panel.add(scrollPane_1);
		
		terms_ta = new JTextArea()
		{
	      public void setEnabled(boolean enabled)
	      {
	        super.setEnabled(enabled);
	        if(enabled == false)
	        {
	          JTextField tf = new JTextField();
	          tf.setEditable(false);
	          setBackground(tf.getBackground());
	        }
	        else setBackground(UIManager.getColor("TextArea.background"));
	      }
	    };
		terms_ta.setEnabled(false);
		terms_ta.setLineWrap(true);
		scrollPane_1.setViewportView(terms_ta);
		
		scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(125, 280, 184, 61);
		panel.add(scrollPane_2);
		
		note_ta = new JTextArea()
		{
	      public void setEnabled(boolean enabled)
	      {
	        super.setEnabled(enabled);
	        if(enabled == false)
	        {
	          JTextField tf = new JTextField();
	          tf.setEditable(false);
	          setBackground(tf.getBackground());
	        }
	        else setBackground(UIManager.getColor("TextArea.background"));
	      }
	    };
		note_ta.setEnabled(false);
		note_ta.setLineWrap(true);
		scrollPane_2.setViewportView(note_ta);
	}

	private void save()
	{
		ArrayList<String> ids = new ArrayList<>();
		ArrayList<String> amounts = new ArrayList<>();
		for (Object[] data : selected)
		{
			ids.add((String) data[0]);
			amounts.add(String.valueOf(data[1]));
		}
		boolean ok = true;
		lblYouMustInsert.setVisible(false);
		String delivery_note = note_ta.getText();
		
		String terms_of_delivery = terms_ta.getText();
		
		String additional_information = add_inf_ta.getText();
		
		
		boolean is_complete = paid_checkbox.isSelected();
		boolean with_delivery = delivery_checkbox.isSelected();
		double special_discount = 0;
		if(!(is_employee))
		{
			String spec_disc = spec_disc_tf.getText();
			if (is_numeric(spec_disc))
			{
				special_discount = Double.parseDouble(spec_disc);
			}
			else if (!(spec_disc.equals("")))
			{
				ok = false;
				lblYouMustInsert.setVisible(true);
			}
		}
		if (ok)
		{
			
			double group_discount = CustomerCollection.get_group_discount(customer_id);
			if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
					"Are you sure you want to register this sale?\nTotal cost is:" + order_ctr.calculate_total_cost_of_order(ids, amounts, special_discount, with_delivery, group_discount),
					"Register sale", JOptionPane.YES_NO_OPTION))
			{
				String id = order_ctr.add_order(with_delivery, delivery_note,additional_information, is_complete,terms_of_delivery, ids, amounts, special_discount,group_discount);
				CustomerCollection.add_order_to_customer(customer_id, id);
				CurrentAccount.add_new_serviced_order(id);
	
				for(int i = 0; i < ids.size(); i++)
				{
					Stock.subtract_amount(ids.get(i), amounts.get(i));
				}
				
				JOptionPane.showMessageDialog(this, "Sale successfully added.",
						"Success", JOptionPane.INFORMATION_MESSAGE);
				dispose();
			}
		}
	}

	private void back()
	{
		SalesUI p = new SalesUI(selected, CustomerCollection.find_customer(customer_id).get_name());
		getDesktopPane().add(p);
		p.setVisible(true);
		dispose();
	}

	private boolean is_numeric(String checker)
	{
		try
		{
			Double.parseDouble(checker);
		}
		catch (NumberFormatException nfe)
		{
			return false;
		}
		return true;
	}
}
